package cube.utils.security;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import cube.data.util.DataUtil;

/**
 * PasswordUtil2
 * 
 * @author abiao
 */
public class PasswordUtil {

    /**
     * 常用密码
     */
    private static final String[] COMMON_PASSWORD = { "", " ", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "123",
            "321", "123456", "654321", "12345678", "87654321", "root", "root123", "root321", "root123456",
            "root654321", "admin", "Admin", "admin123", "Admin123", "admin321", "Admin321", "admin111", "Admin111",
            "mysql", "!@#$%^", "^%$#@!", "qwerty", "ytrewq", "asdfgh", "hgfdsa", "zxcvbn", "nbvcxz", "jkl;'\\",
            "1234/.,mnb" };

    /**
     * md5Digest
     */
    private static MessageDigest md5Digest = null;

    /**
     * sha1Digest
     */
    private static MessageDigest sha1Digest = null;

    /**
     * md5加密
     */
    public static String md5(String plain) {
        if (md5Digest == null) {
            md5Digest = initMessageDigest("MD5");
        }
        return messageDigestEncode(md5Digest, plain);
    }

    /**
     * sha1加密
     */
    public static String sha1(String plain) {
        if (sha1Digest == null) {
            sha1Digest = initMessageDigest("SHA1");
        }
        return messageDigestEncode(sha1Digest, plain);
    }

    /**
     * 生成消息编码
     */
    private static String messageDigestEncode(MessageDigest md, String plain) {
        md.update(plain.getBytes());
        return DataUtil.toHexString(md.digest());
    }

    /**
     * 初始化加密器
     */
    private static MessageDigest initMessageDigest(String algorithm) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return messageDigest;
    }

    /**
     * 通过常见md5值猜测明文
     */
    public static String guess(String md5) {
        Map<String, String> md5Map = new HashMap<String, String>();
        for (String plain : COMMON_PASSWORD) {
            md5Map.put(md5(plain), plain);
        }
        return md5Map.get(md5);
    }
}
